package au.org.ala.collectors

import org.codehaus.groovy.grails.web.servlet.HttpHeaders
import au.com.bytecode.opencsv.CSVWriter

class AdminController {

    def dataLoadService

    def index = { }

    def load = {
        def res = dataLoadService.loadFromCSV("/data/collectors/anbg.csv")
        render "datalines=${res.dataLines}<br/>inserts=${res.inserts}<br/>failures=${res.failures}"
    }

    def updateBiographyLinks = {
        int count = 0
        Person.list().each {
            if (it.biog) {
                def match = "href='/biography/"
                if (it.biog =~ match) {
                    println "updating biog for ${it.getName()}"
                    count++
//                    it.biog = it.biog.replaceAll(match,'href="')
                    it.biog = it.biog.replaceAll(match,"href='")
                    println it.biog
                    it.save()
                }

            }
        }
        render "updated ${count}"
    }

    def dump = {
        response.addHeader HttpHeaders.CONTENT_TYPE, 'text/csv'
        Writer w = response.getWriter()
        CSVWriter wr = new CSVWriter(w)
        String[] header = ['familyName','foreNames','areaOfInterest','periodOfActivity','yearOfBirth','yearOfDeath',
        'imageUri','personContributed','living','yearOfBirthUncertain','yearOfDeathUncertain','lastUpdated','biog']
        wr.writeNext(header)
        Person.list([sort:'familyName']).each {
            String[] values = [it.familyName, it.foreNames, it.areaOfInterest, it.periodOfActivity, it.yearOfBirth,
            it.yearOfDeath, it.imageUri, it.personContributed, it.living, it.yearOfBirthUncertain,
            it.yearOfDeathUncertain, it.lastUpdated, it.biog]
            wr.writeNext values
        }
        wr.close()
        render ""
    }

    def trim = {
        def field = params.field
        if (field) {
            Person.list().each {
                def value = it."${field}"
                if (value instanceof String) {
                    //test += "${value} -> ${value.trim()}\n"
                    it."${field}" = value.trim()
                    it.save()
                }
            }
            render "done"
        } else {
            render "You must specify a field to trim."
        }
    }

    def setType = {
        def illustrators = []
        def collectors = []
        Person.list().each {
            if (it.areaOfInterest?.toLowerCase() =~ "illustrator" || it.areaOfInterest?.toLowerCase() =~ "artist") {
                illustrators << it
                if (it.areaOfInterest?.toLowerCase() =~ "botanist" ||
                    it.areaOfInterest?.toLowerCase() =~ "naturalist" ||
                    it.areaOfInterest?.toLowerCase() =~ "gardener" ||
                    it.areaOfInterest?.toLowerCase() =~ "collector" ||
                    it.areaOfInterest?.toLowerCase() =~ "collected" ||
                    it.areaOfInterest?.toLowerCase() =~ "orchidologist" ||
                    it.areaOfInterest?.toLowerCase() =~ "mycologist" ||
                    it.areaOfInterest?.toLowerCase() =~ "conchologist" ||
                    it.areaOfInterest?.toLowerCase() =~ "scientist" ||
                    it.areaOfInterest?.toLowerCase() =~ "agronomist" ||
                    it.areaOfInterest?.toLowerCase() =~ "horticulturist" ||
                    it.areaOfInterest?.toLowerCase() =~ "nurseryman") {
                    collectors << it
                }
            }
            else {
                collectors << it
            }
        }
        illustrators.each {
            addCategory it, "illustrator"
        }
        collectors.each {
            addCategory it, "collector"
        }
        render "done"
    }

    def addCategory(Person per, cat) {
        if (per.categories) {
            // only add if not present
            if (!(per.categories =~ cat)) {
                per.categories += " " + cat
                per.save()
            }
        }
        else {
            per.categories = cat
            per.save()
        }
    }
}
